import { ref } from 'vue'
import { ElMessage } from 'element-plus'

// 同步统计
const syncStats = ref({
  bank: 0,
  salesOrder: 0,
  purchaseOrder: 0,
  incomingInvoice: 0,
  outgoingInvoice: 0,
  announcement: 0,
  total: 0
})

// 同步历史
const syncHistory = ref([])

// 同步失败的数据
const failedSyncData = ref([])

// URL匹配函数
function isUrlMatch(url: string, pattern: string, matchType?: string): boolean {
  // 如果没有指定匹配类型，默认使用includes
  if (!matchType || matchType === 'includes') {
    return url.includes(pattern);
  }
  
  // 精确匹配
  if (matchType === 'exact') {
    // 移除查询参数后进行精确匹配
    const urlWithoutQuery = url.split('?')[0];
    return urlWithoutQuery === pattern;
  }
  
  // 前缀匹配
  if (matchType === 'startsWith') {
    return url.startsWith(pattern);
  }
  
  // 后缀匹配
  if (matchType === 'endsWith') {
    return url.endsWith(pattern);
  }
  
  // 正则表达式匹配
  if (matchType === 'regex') {
    try {
      const regex = new RegExp(pattern);
      return regex.test(url);
    } catch (e) {
      console.error('❌ 正则表达式错误:', pattern, e);
      return false;
    }
  }
  
  // 默认使用includes
  return url.includes(pattern);
}

// 获取真实同步统计数据
const fetchSyncStats = () => {
  chrome.storage.local.get(['capturedRequests', 'interceptionRules'], (result) => {
    // 确保syncStats.value存在且有正确的结构
    if (!syncStats.value || typeof syncStats.value !== 'object') {
      syncStats.value = {
        bank: 0,
        salesOrder: 0,
        purchaseOrder: 0,
        incomingInvoice: 0,
        outgoingInvoice: 0,
        announcement: 0,
        total: 0
      };
    } else {
      // 确保所有必需的属性都存在
      if (typeof syncStats.value.bank !== 'number') syncStats.value.bank = 0;
      if (typeof syncStats.value.salesOrder !== 'number') syncStats.value.salesOrder = 0;
      if (typeof syncStats.value.purchaseOrder !== 'number') syncStats.value.purchaseOrder = 0;
      if (typeof syncStats.value.incomingInvoice !== 'number') syncStats.value.incomingInvoice = 0;
      if (typeof syncStats.value.outgoingInvoice !== 'number') syncStats.value.outgoingInvoice = 0;
      if (typeof syncStats.value.announcement !== 'number') syncStats.value.announcement = 0;
      if (typeof syncStats.value.total !== 'number') syncStats.value.total = 0;
    }
    
    if (result && result.capturedRequests && Array.isArray(result.capturedRequests)) {
      const data = result.capturedRequests
      
      // 获取拦截规则
      let interceptionRules: any[] = [];
      if (result.interceptionRules) {
        interceptionRules = Array.isArray(result.interceptionRules) ? result.interceptionRules : Object.values(result.interceptionRules);
      }
      
      // 分类统计
      let bankCount = 0
      let salesOrderCount = 0
      let purchaseOrderCount = 0
      let incomingInvoiceCount = 0
      let outgoingInvoiceCount = 0
      let announcementCount = 0
      
      data.forEach((item: any) => {
        if (item.url) {
          // 根据拦截规则匹配数据类型
          let matched = false;
          for (const rule of interceptionRules) {
            if (rule.enabled !== false && isUrlMatch(item.url, rule.urlPattern, rule.matchType)) {
              // 根据规则的数据类型字段确定数据类型
              if (rule.dataType) {
                switch (rule.dataType) {
                  case 'bank':
                    bankCount++;
                    matched = true;
                    break;
                  case 'sales_order':
                    salesOrderCount++;
                    matched = true;
                    break;
                  case 'purchase_order':
                    purchaseOrderCount++;
                    matched = true;
                    break;
                  case 'incoming_invoice':
                    incomingInvoiceCount++;
                    matched = true;
                    break;
                  case 'outgoing_invoice':
                    outgoingInvoiceCount++;
                    matched = true;
                    break;
                  case 'announcement':
                    announcementCount++;
                    matched = true;
                    break;
                }
              }
              if (matched) break;
            }
          }
          
          // 如果没有匹配到规则，尝试根据URL模式判断
          if (!matched) {
            if (item.url.includes('/uc-server/service/hzDealDetailReport/hzDealDetailQuery')) {
              bankCount++;
            } else if (item.url.includes('/api/mall/order/list') && !item.url.includes('purchase')) {
              salesOrderCount++;
            } else if (item.url.includes('purchase') || item.url.includes('procurement')) {
              purchaseOrderCount++;
            } else if (item.url.includes('/szzhzz/qlfpcx/v1/queryFpjcxx')) {
              incomingInvoiceCount++;
            } else if (item.url.includes('/szzhzz/fpxxcx/v1/queryFpxx')) {
              outgoingInvoiceCount++;
            } else if (item.url.includes('/announcement/lobby/queryPage')) {
              announcementCount++;
            }
          }
        }
      })
      
      syncStats.value = {
        bank: bankCount,
        salesOrder: salesOrderCount,
        purchaseOrder: purchaseOrderCount,
        incomingInvoice: incomingInvoiceCount,
        outgoingInvoice: outgoingInvoiceCount,
        announcement: announcementCount,
        total: data.length
      }
    } else {
      // 如果没有数据，设置默认值
      syncStats.value = {
        bank: 0,
        salesOrder: 0,
        purchaseOrder: 0,
        incomingInvoice: 0,
        outgoingInvoice: 0,
        announcement: 0,
        total: 0
      }
    }
  })
}

// 获取真实的同步历史记录
const fetchSyncHistory = () => {
  // 从存储中获取真实的同步历史
  chrome.storage.local.get(['capturedRequests', 'interceptionRules', 'failedSyncData'], (result) => {
    // 确保syncHistory.value存在
    if (!syncHistory.value || !Array.isArray(syncHistory.value)) {
      syncHistory.value = [];
    }
    
    // 确保failedSyncData.value存在
    if (!failedSyncData.value || !Array.isArray(failedSyncData.value)) {
      failedSyncData.value = [];
    }
    
    if (result && result.capturedRequests && Array.isArray(result.capturedRequests)) {
      const data = result.capturedRequests
      
      // 获取拦截规则
      let interceptionRules: any[] = [];
      if (result.interceptionRules) {
        interceptionRules = Array.isArray(result.interceptionRules) ? result.interceptionRules : Object.values(result.interceptionRules);
      }
      
      // 获取同步失败的数据
      if (result.failedSyncData && Array.isArray(result.failedSyncData)) {
        failedSyncData.value = result.failedSyncData;
      }
      
      // 创建同步历史记录
      const history = []
      let id = 1
      
      // 按时间分组，创建同步记录
      const groupedByDate: any = {}
      data.forEach((item: any) => {
        const date = new Date(item.timestamp).toDateString()
        if (!groupedByDate[date]) {
          groupedByDate[date] = []
        }
        groupedByDate[date].push(item)
      })
      
      // 为每个日期创建同步记录
      Object.keys(groupedByDate).slice(0, 5).forEach(date => {
        const items = groupedByDate[date]
        
        // 分类统计
        const bankItems = items.filter((item: any) => {
          // 根据规则或URL判断是否为银行数据
          for (const rule of interceptionRules) {
            if (rule.enabled !== false && (rule.dataType === 'bank' || rule.name.includes('银行')) && 
                item.url && isUrlMatch(item.url, rule.urlPattern, rule.matchType)) {
              return true
            }
          }
          return item.url && item.url.includes('/uc-server/service/hzDealDetailReport/hzDealDetailQuery')
        })
        
        const salesOrderItems = items.filter((item: any) => {
          // 根据规则或URL判断是否为销售订单数据
          for (const rule of interceptionRules) {
            if (rule.enabled !== false && (rule.dataType === 'sales_order' || (rule.name.includes('订单') && !rule.name.includes('采购'))) && 
                item.url && isUrlMatch(item.url, rule.urlPattern, rule.matchType)) {
              return true
            }
          }
          return item.url && item.url.includes('/api/mall/order/list') && !item.url.includes('purchase')
        })
        
        const purchaseOrderItems = items.filter((item: any) => {
          // 根据规则或URL判断是否为采购订单数据
          for (const rule of interceptionRules) {
            if (rule.enabled !== false && (rule.dataType === 'purchase_order' || rule.name.includes('采购')) && 
                item.url && isUrlMatch(item.url, rule.urlPattern, rule.matchType)) {
              return true
            }
          }
          return item.url && (item.url.includes('purchase') || item.url.includes('procurement'))
        })
        
        const incomingInvoiceItems = items.filter((item: any) => {
          // 根据规则或URL判断是否为进项发票数据
          for (const rule of interceptionRules) {
            if (rule.enabled !== false && (rule.dataType === 'incoming_invoice' || rule.name.includes('进项')) && 
                item.url && isUrlMatch(item.url, rule.urlPattern, rule.matchType)) {
              return true
            }
          }
          return item.url && item.url.includes('/szzhzz/qlfpcx/v1/queryFpjcxx')
        })
        
        const outgoingInvoiceItems = items.filter((item: any) => {
          // 根据规则或URL判断是否为销项发票数据
          for (const rule of interceptionRules) {
            if (rule.enabled !== false && (rule.dataType === 'outgoing_invoice' || rule.name.includes('销项')) && 
                item.url && isUrlMatch(item.url, rule.urlPattern, rule.matchType)) {
              return true
            }
          }
          return item.url && item.url.includes('/szzhzz/fpxxcx/v1/queryFpxx')
        })
        
        const announcementItems = items.filter((item: any) => {
          // 根据规则或URL判断是否为公告数据
          for (const rule of interceptionRules) {
            if (rule.enabled !== false && (rule.dataType === 'announcement' || rule.name.includes('公告')) && 
                item.url && isUrlMatch(item.url, rule.urlPattern, rule.matchType)) {
              return true
            }
          }
          return item.url && item.url.includes('/announcement/lobby/queryPage')
        })
        
        // 创建同步记录
        if (bankItems.length > 0) {
          history.push({
            id: id++,
            type: '🏦 银行流水',
            timestamp: new Date(bankItems[0].timestamp).toLocaleString('zh-CN'),
            message: `同步成功`,
            success: true,
            count: bankItems.length
          })
        }
        
        if (salesOrderItems.length > 0) {
          history.push({
            id: id++,
            type: '💰 销售订单',
            timestamp: new Date(salesOrderItems[0].timestamp).toLocaleString('zh-CN'),
            message: `同步成功`,
            success: true,
            count: salesOrderItems.length
          })
        }
        
        if (purchaseOrderItems.length > 0) {
          history.push({
            id: id++,
            type: '🛒 采购订单',
            timestamp: new Date(purchaseOrderItems[0].timestamp).toLocaleString('zh-CN'),
            message: `同步成功`,
            success: true,
            count: purchaseOrderItems.length
          })
        }
        
        if (incomingInvoiceItems.length > 0) {
          history.push({
            id: id++,
            type: '📥 进项发票',
            timestamp: new Date(incomingInvoiceItems[0].timestamp).toLocaleString('zh-CN'),
            message: `同步成功`,
            success: true,
            count: incomingInvoiceItems.length
          })
        }
        
        if (outgoingInvoiceItems.length > 0) {
          history.push({
            id: id++,
            type: '📤 销项发票',
            timestamp: new Date(outgoingInvoiceItems[0].timestamp).toLocaleString('zh-CN'),
            message: `同步成功`,
            success: true,
            count: outgoingInvoiceItems.length
          })
        }
        
        if (announcementItems.length > 0) {
          history.push({
            id: id++,
            type: '📢 公告信息',
            timestamp: new Date(announcementItems[0].timestamp).toLocaleString('zh-CN'),
            message: `同步成功`,
            success: true,
            count: announcementItems.length
          })
        }
      })
      
      // 添加失败同步记录
      if (failedSyncData.value.length > 0) {
        failedSyncData.value.forEach((item: any) => {
          history.push({
            id: id++,
            type: item.dataType === 'bank' ? '🏦 银行流水' : 
                 item.dataType === 'sales_order' ? '💰 销售订单' : 
                 item.dataType === 'purchase_order' ? '🛒 采购订单' : 
                 item.dataType === 'incoming_invoice' ? '📥 进项发票' : 
                 item.dataType === 'outgoing_invoice' ? '📤 销项发票' : 
                 item.dataType === 'announcement' ? '📢 公告信息' : '📦 未知数据',
            timestamp: new Date(item.timestamp).toLocaleString('zh-CN'),
            message: `同步失败: ${item.errorMessage || '未知错误'}`,
            success: false,
            count: 1,
            data: item // 保存失败的数据，用于重新同步
          })
        })
      }
      
      // 按时间倒序排列
      syncHistory.value = history.sort((a: any, b: any) => 
        new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime()
      ).slice(0, 10)
    } else {
      // 如果没有数据，设置为空数组
      syncHistory.value = []
    }
  })
}

// 初始化数据
const initSyncData = () => {
  fetchSyncStats()
  fetchSyncHistory()
}

// 同步银行数据
const syncBankData = () => {
  ElMessage.info('正在同步银行数据...')
  // 模拟同步过程
  setTimeout(() => {
    ElMessage.success('银行数据同步完成')
    // 重新获取统计数据
    fetchSyncStats()
    fetchSyncHistory()
  }, 1000)
}

// 同步订单数据
const syncOrderData = () => {
  ElMessage.info('正在同步订单数据...')
  // 模拟同步过程
  setTimeout(() => {
    ElMessage.success('订单数据同步完成')
    // 重新获取统计数据
    fetchSyncStats()
    fetchSyncHistory()
  }, 1000)
}

// 同步发票数据
const syncInvoiceData = () => {
  ElMessage.info('正在同步发票数据...')
  // 模拟同步过程
  setTimeout(() => {
    ElMessage.success('发票数据同步完成')
    // 重新获取统计数据
    fetchSyncStats()
    fetchSyncHistory()
  }, 1000)
}

// 同步公告数据
const syncAnnouncementData = () => {
  ElMessage.info('正在同步公告数据...')
  // 模拟同步过程
  setTimeout(() => {
    ElMessage.success('公告数据同步完成')
    // 重新获取统计数据
    fetchSyncStats()
    fetchSyncHistory()
  }, 1000)
}

// 同步所有数据
const syncAllData = () => {
  ElMessage.info('正在同步所有数据...')
  // 模拟同步过程
  setTimeout(() => {
    ElMessage.success('所有数据同步完成')
    // 重新获取统计数据
    fetchSyncStats()
    fetchSyncHistory()
  }, 2000)
}

// 重新同步失败的数据
const retryFailedSync = (dataItem: any = null) => {
  if (dataItem) {
    // 重新同步单个失败的数据
    ElMessage.info(`正在重新同步 ${dataItem.dataType} 数据...`)
    // 模拟同步过程
    setTimeout(() => {
      ElMessage.success(`${dataItem.dataType} 数据重新同步成功`)
      // 从失败列表中移除
      failedSyncData.value = failedSyncData.value.filter((item: any) => item.id !== dataItem.id)
      // 更新存储
      chrome.storage.local.set({ failedSyncData: failedSyncData.value })
      // 重新获取统计数据
      fetchSyncStats()
      fetchSyncHistory()
    }, 1000)
  } else {
    // 重新同步所有失败的数据
    if (failedSyncData.value.length === 0) {
      ElMessage.info('没有失败的同步数据')
      return
    }
    
    ElMessage.info(`正在重新同步 ${failedSyncData.value.length} 个失败的数据...`)
    // 模拟同步过程
    setTimeout(() => {
      ElMessage.success('所有失败数据重新同步成功')
      // 清空失败列表
      failedSyncData.value = []
      // 更新存储
      chrome.storage.local.set({ failedSyncData: failedSyncData.value })
      // 重新获取统计数据
      fetchSyncStats()
      fetchSyncHistory()
    }, 2000)
  }
}

// 手动同步单个数据项
const manualSyncDataItem = (dataItem: any) => {
  ElMessage.info(`正在手动同步数据项...`)
  // 模拟同步过程
  setTimeout(() => {
    ElMessage.success('数据项同步成功')
    // 重新获取统计数据
    fetchSyncStats()
    fetchSyncHistory()
  }, 1000)
}

export function useSync() {
  return {
    syncStats,
    syncHistory,
    failedSyncData,
    syncBankData,
    syncOrderData,
    syncInvoiceData,
    syncAnnouncementData,
    syncAllData,
    initSyncData,
    fetchSyncStats,
    fetchSyncHistory,
    retryFailedSync,
    manualSyncDataItem
  }
}